package sort.leetcode.medium;

/**
 * @author bruin_du
 * @description 链表排序
 * @date 2022/9/1 23:38
 **/
public class OfferII077_SortList {
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) return head;
        return mergeList(head, null);
    }

    private ListNode mergeList(ListNode head, ListNode tail) {
        // 只有一个结点继续遍历终点就有可能为空
        if (head == null) return head;
        // 如果只有一个结点的时候
        if (head.next == tail) {
            head.next = null;
            return head;
        }
        // 寻找中间结点,注意结尾值tail,否则会栈溢出
        ListNode fast = head, slow = head;
        while (fast != tail) {
            fast = fast.next;
            slow = slow.next;
            // 建议这么写,好判断出递归的条件
            if (fast != tail) {
                fast = fast.next;
            }
        }
        ListNode mid = slow;
        ListNode list1 = mergeList(head, mid);
        ListNode list2 = mergeList(mid, tail);
        // 合并链表
        return sort(list1, list2);
    }

    private ListNode sort(ListNode list1, ListNode list2) {
        ListNode dummyHead = new ListNode(0);
        ListNode cur = dummyHead;
        while (list1 != null && list2 != null) {
            if (list1.val > list2.val) {
                cur = cur.next = list2;
                list2 = list2.next;
            } else {
                cur = cur.next = list1;
                list1 = list1.next;
            }
        }
        if (list2 != null) {
            list1 = list2;
        }
        cur.next = list1;
        return dummyHead.next;
    }
}
